package two.chapter_1.c1_2;

import edu.princeton.cs.algs4.StdOut;
import two.chapter_1.c1_1.Gcd;

public final class Rational {

    private final int numerator;
    private final int denominator;
    private static int MAX=Integer.MAX_VALUE;
    private static int MIN=Integer.MIN_VALUE;

    public Rational(int numerator, int denominator) {
        if (denominator ==0){
            throw new ArithmeticException("Divide by zero");
        }

        if (denominator<0){
            numerator=-numerator;
            denominator=-denominator;
        }

        Gcd gcd = new Gcd();
        int g = gcd.gcd(numerator, denominator);
        this.numerator = numerator / g;
        this.denominator = denominator / g;
    }
    private boolean isOverflow(int a){
        return a<=MAX && a>=MIN;
    }
    public Rational plus(Rational b) {

        Rational result;
        if (denominator == b.denominator) {
            //分母相等分子直接相加
            result = new Rational(numerator + b.numerator, denominator);
        } else {
            int newnumerator = numerator * b.denominator;
            int newDenominator = denominator * b.denominator;

            int newThatnumerator = b.numerator * denominator;
            result = new Rational(newnumerator + newThatnumerator, newDenominator);
        }
        assert isOverflow(result.numerator) : "Plus overflow";
        return result;
    }

    public Rational minus(Rational b) {
        Rational target = new Rational(-b.numerator, b.denominator);
        return plus(target);
    }

    public Rational times(Rational b) {
        Rational result = new Rational(numerator * b.numerator, denominator * b.denominator);
        assert isOverflow(result.numerator) : "Times overflow";
        assert isOverflow(result.denominator) : "Times overflow";
        return result;
    }

    public Rational devides(Rational b) {
        Rational target = new Rational( b.denominator,b.numerator);
        return times(target);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj ==null) return false;

        if (getClass() !=obj.getClass())return false;

        Rational that= (Rational) obj;
        if (numerator!=that.numerator){
            return false;
        }
        if (denominator!=that.denominator){
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return numerator + "/" + denominator;
    }
}
